<template>
  <div>
    <!-- 搜索栏 ： 两个搜索框  搜索按钮  添加菜单按钮  批量删除   -->
	<el-row>
	  <el-col :span="1"></el-col>
	  <el-col :span="4">
		   <el-input placeholder="请输入编号搜索" v-model="query.empCode"/>
	  </el-col>
	  <el-col :span="4">
	  		<el-input placeholder="请输入名称搜索" v-model="query.empName"/>
	  </el-col>
	  <el-col :span="4">
	  		<el-input placeholder="请输入类型搜索" v-model="query.empType"/>
	  </el-col>
	  <el-col :span="2">
	  		<el-button type="primary" plain @click="getByPage">搜索</el-button>
	  </el-col>
	  <el-col :span="3">
	  		<el-button type="success" plain @click="showDialog">新增菜单</el-button>
	  </el-col>
	  <el-col :span="3">
	  		<el-button type="danger" plain @click="handleBatchDel">批量删除</el-button>
	  </el-col>
	  
    </el-row>
	<!-- 表格 -->
	<el-row>
		<el-col :offset="1" :span="20">

			<el-tree
				:data="treeData"
				show-checkbox
				node-key="id"
				:props="defaultProps"
				default-expand-all
				:expand-on-click-node="false"
				@check="handleCheck"
			>
			<template #default="{ node, data }">
				<span class="custom-tree-node">
					<!-- 如果使用node.label  需要添加上面的 :props="defaultProps"
					 如果使用data.name就不需要 -->
				<!-- <span>{{ node.label }}-- {{data.name}}</span> -->
				<span>{{ node.label }}</span>
					<span >
						<a @click="edit(data)"> 编辑 </a>
						<a v-if="!data.parentId" @click="append(data)"> 新增子菜单 </a>
						<a v-if="!data.children" style="margin-left: 8px" @click="remove(node, data)"> 删除 </a>
					</span>
				</span>
			</template>
			</el-tree>

		</el-col>
	</el-row>

	<!-- 编辑菜单信息的对话框  用于添加和修改 -->
	<el-dialog v-model="dialogFormVisible" title="编辑菜单信息" width="500" draggable>
		<el-form :model="form">
		  <el-form-item label="菜单名称" :label-width="formLabelWidth">
			  <el-input v-model.trim="form.name" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="菜单组件" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.component" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="菜单url" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.url" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="菜单图标" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.icon" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="菜单顺序" :label-width="formLabelWidth">
		  	  <el-input-number v-model.number="form.orderIndex" min="1"/>
		  </el-form-item>
		  <el-form-item label="父级菜单" :label-width="formLabelWidth">
		  	  <el-select v-model.number="form.parentId" placeholder="请选择父菜单" @focus="getLevel1Menu">
				<el-option :value="null">无</el-option>
				<el-option v-for="m in level1Menu" :key="m.id" :value="m.id" :label="m.name">{{m.name}}</el-option>
			  </el-select>
		  </el-form-item>
		</el-form>
		<template #footer>
		  <div class="dialog-footer">
			<el-button @click="dialogFormVisible = false">取消</el-button>
			<el-button type="primary" @click="addOrUpdate">
			  确认提交
			</el-button>
		  </div>
		</template>
  </el-dialog>
	
  </div>
</template>

<script setup>
import httpRequest from '../../common/index.js';
import { onMounted, ref, getCurrentInstance, computed, watch } from 'vue';
import { ElMain, ElMessage,ElMessageBox } from 'element-plus';
import { nanoid } from 'nanoid';
import { Check, Plus } from '@element-plus/icons-vue'
import Node from 'element-plus/es/components/tree/src/model/node'



  let {proxy} = getCurrentInstance();

  let baseUrl = proxy.$baseUrl;

  //对话框是否显示
  let dialogFormVisible = ref(false);
  let formLabelWidth = ref('100px');
  
  //表单数据 添加和修改
  let form = ref({
	  name: '',
	  component: '',
	  url: '',
	  icon: '',
	  orderIndex: 1,
	  parentId: null,
  })
  
  //生成菜单账号的函数
  const generateAccount = ()=>{
	  let account = nanoid().replaceAll("_","").replaceAll("-","");
	  console.log(account);
	  let startIndex = Math.floor(Math.random()*10);
	  account = account.substring(startIndex,startIndex+9);
	  console.log(account);
	  return account;
  }
  
  //点新增菜单信息按钮弹出对话框
  const showDialog = ()=>{
	  
	  dialogFormVisible.value = true;
	  //数据清除
	  form.value = {
		name: '',
		component: '',
		url: '',
		icon: '',
		orderIndex: 1,
		parentId: null,
	  };
	  //清空之前上传的图片的回显链接
	  imageUrl.value = '';
  }

  //分页+搜索条件
  let query = ref({
	  current: 1,
	  size: 5,
	  empCode: '',
	  empName: '',
	  empType: '',
  })
  
  //分页对象 total  pages  data(集合)
  let pb = ref({
	  total: 0,
	  pages: 0,
	  records: []
  })

  //分页查询菜单信息
  const getByPage = ()=>{

	httpRequest(
			proxy,
			'post',
			'/menu/page',
			query.value,
			(resultBean)=>{
				pb.value = resultBean.data;
			})

  }

  //**************存放所有一级菜单的集合********************** */
  const level1Menu = ref([]);

  //*****************查询所有的一级菜单************************ */
  const getLevel1Menu = ()=>{
	httpRequest(
			proxy,
			'get',
			'/menu/level1',
			{},
			(resultBean)=>{
				level1Menu.value = resultBean.data;
			})
  }

  //**************新增子菜单*** data是一级菜单*********** */
  const append = (data)=>{
	dialogFormVisible.value = true;
	  //数据清除
	  form.value = {
		name: '',
		component: data.component+'/',
		url: '',
		icon: '',
		orderIndex: 1,
		parentId: data.id,
	  };
  }

  /***************编辑菜单之前的数据回显***************** */
  const edit = (data)=>{
	console.log(data);
	dialogFormVisible.value = true;
	form.value = data;
  }
  
  //添加或修改
  const addOrUpdate = ()=>{

	httpRequest(
			proxy,
			'post',
			'/menu',
			form.value,
			(resultBean)=>{
				getTree();
			    dialogFormVisible.value = false;
			    ElMessage.success('保存菜单信息成功');
			})
  }
  
  //处理删除
  const remove = (node,data)=>{
	console.log(data);
	//这里直接删除就行了
	proxy.$axios({
		method:'post',
		url:'/menu/delete',
		data:data
	}).then(res=>{
		let resultBean=res.data;
		if(resultBean.code==200) {
			ElMessage.success('删除成功');
			getTree();
		} else {
			ElMessage.error(resultBean.msg);
		}
	}).catch(error=>{
		ElMessage.message(error.message);
	})
	 
  }
  
  // const selectable = (row,index)=>{
	 //  console.log('selectable',row,index);
	 //  return true;
  // }
  
  //选中项的id集合
  let selectOptions = ref([]);
  //这里再自己写一个批量删除的函数，用于接受地址栏的参数
  	//通过这样可以拿到节点也就是整个数据还可以拿到这个id
	const handleCheck = (checkedNodes, checkedKeys) => {
      console.log('选中项改变', checkedKeys.checkedKeys);
	  selectOptions.value=checkedKeys.checkedKeys;
    };
  //批量删除的函数
  const handleBatchDel = ()=>{
	  console.log(selectOptions.value);
	  if(selectOptions.value.length==0){
		  ElMessage.info('请选中至少一条记录之后再进行删除');  
		  return;
	  }
	  
	  ElMessageBox.confirm(
	      '您确定要删除选中的菜单信息吗？',
	      '删除提示',
	      {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        type: 'warning',
	      }
	    )
	      .then(() => {

			console.log(selectOptions.value);
			console.log(typeof(selectOptions.value));
			console.log(JSON.stringify(selectOptions.value));

			let str = JSON.stringify(selectOptions.value);
			str = str.substring(1,str.length-1);
	  			  
	  			  //确定删除
				proxy.$axios({
					method: 'post',
					url: '/menu/deleteBatch/'+str,
				}).then(res=>{
					let resultBean = res.data;
					if(resultBean.code == 200){
						ElMessage.success('删除成功');  
						getTree();
					}else{
						ElMessage.error(resultBean.msg);
					}
				})
	  			
	  			  
	      })
	      .catch(() => {
	           ElMessage.info('取消删除');
	      })
  }
  
  //上传图片的回显链接
  let imageUrl = ref('');
  
  //上传成功之后的回调
  const handleAvatarSuccess = (response,uploadFile)=>{
	  ElMessage.success('上传成功');
	  console.log('上传成功，',response,uploadFile);
	  //负责上传完成 图片回显
	  imageUrl.value = response.data;
	  //将上传成功的链接放入form表单， 添加或修改时会携带到服务端
	  form.value.MenuImg = response.data;
  }
  
  //上传之前预检文件
  const beforeAvatarUpload = (rawFile)=>{
	  //文件类型不符合要求 或者 文件大小超过要求  都不能上传
	  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
	      ElMessage.error('Avatar picture must be JPG format!')
	      return false
	    } else if (rawFile.size / 1024 / 1024 > 5) {
	      ElMessage.error('Avatar picture size can not exceed 5MB!')
	      return false
	    }
		//可以上传
	    return true
  }


  //*******tree组件显示节点名称默认使用label  将label改成name******** */
  const defaultProps = {
	 label: 'name',

  };

  //****************菜单树的数据**************************** */
  const treeData = ref([]);

  //**************查询菜单树结构********************** */
  const getTree = ()=>{
	httpRequest(
			proxy,
			'get',
			'/menu/all/tree',
			{},
			(resultBean)=>{
				treeData.value = resultBean.data;
			})
  } 
  
  onMounted(()=>{
	  getByPage();
	  getTree();
	  getLevel1Menu();
  })


</script>

<style scoped>
	.avatar-uploader .avatar {
	  width: 100px;
	  height: 100px;
	  display: block;
	}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}


.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

</style>